//
//  WEXStatusListViewModels.swift
//  microBlog
//
//  Created by apple on 16/4/20.
//  Copyright © 2016年 Hill. All rights reserved.
//

import UIKit
import SDWebImage

class WEXStatusListViewModel: NSObject {
    
    
    
    // 记录数组数据
    var statusArray: [WEXStatusViewModel]?
    
    //    var statuesArray: [WEXStatusModel]?
    
    // MARK: - 加载数据
    func loadData(isPull: Bool,finished: (isSuccess: Bool, count: Int)->()){
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        var max_id: Int64 = 0
        
        var since_id: Int64 = 0
//        判断是否是最后一个id
        if isPull {
            
            max_id = statusArray?.last?.status?.id ?? 0
            
//            放置最后一条微博内容重复加载
            if max_id != 0 {
                
                max_id--
                
            }
            
        }else{
            
            since_id = statusArray?.first?.status?.id ?? 0
            
        }
        
        
//        设置参数
        let parames = [
            
            "access_token" : WEXUserAccountViewModel.sharedViewModel.accessToken ?? "",
            "max_id": "\(max_id)",
            "since_id": "\(since_id)"
        ]
        
//        请求数据
        WEXNetworkTools.sharedTools.request(.Get, urlString: urlString, parameters: parames, finished: { (responseObject, error) -> () in
            
            if error != nil{
                finished(isSuccess: false, count: 0)
                
                return
            }
            
//            print(parames)
            
            //            print(responseObject)
            //                取出最外层字典
            guard let respDict = responseObject as? [String: AnyObject] else{
                finished(isSuccess: false, count: 0)
                return
            }
            
            //                取出字典数组
            guard let dicts = respDict["statuses"] as? [[String: AnyObject]] else{
                finished(isSuccess: false,count:  0)
                return
            }
            
            //                设置临时数组
            var tempArray = [WEXStatusViewModel]()
            
            for value in dicts {
                //                    字典转模型
                let model = WEXStatusModel(dict: value)
                let viewModel = WEXStatusViewModel()
                
                viewModel.status = model
                
                tempArray.append(viewModel)
            }
            
//            self.statusArray = tempArray
            
//            判断数组如果为空，实例化一个数组
            if self.statusArray == nil {
                
                self.statusArray = [WEXStatusViewModel]()
//                print("nil ---- \(self.statusArray)")
            }
            
            
            if isPull {
                
                self.statusArray = self.statusArray! + tempArray
                
//                print("ispull ---- \(self.statusArray)")
            }else{
                
                self.statusArray = tempArray + self.statusArray!
//                print("else ---- \(self.statusArray)")
            }
            
            
            //            finished(isSuccess: true)
            
//            调用下载图片方法
            self.cacheSingleImage(tempArray, finished: finished)
            
            
        })
        
        
    }
    
    
    // MARK: - 下载图片
    private func cacheSingleImage(array: [WEXStatusViewModel] , finished:(isSuccess: Bool,count: Int)->()){
        
//        创建任务组
        let group = dispatch_group_create()
        
        for value in array {
            
//            获取原创微博的数据，还是转发微博的数据
            let originalPicUrl = value.status?.pic_urls
            let retweetPicUrl = value.status?.retweeted_status?.pic_urls
            
//            通过三目运算符进行判断picurl
            let picUrl = (originalPicUrl == nil || originalPicUrl!.count == 0 ) ? retweetPicUrl : originalPicUrl
            
            
            if picUrl?.count == 1 {
//                获取下载地址
                let urlSrting = picUrl?.first?.thumbnail_pic
                
//                将任务加入到组中
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urlSrting ?? ""), options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                    
//                    更新单张配图的尺寸
                    value.updateSinglePicSize()
                    
//                    将任务从组中移除
                    dispatch_group_leave(group)
                })
            }
            
            
        }
        
//        组内所有任务完成
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
           
//            回调通知控制器刷新
            finished(isSuccess: true, count: array.count)
        }
        
        
        
    }
}
